import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_comment_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/widgets/comment/comment_refer_widget.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 获取评论列表
class CommentList extends StatefulWidget {
  final int id;
  final int type;
  final bool shrinkWrap;


  const CommentList({Key key, @required this.id, @required this.type, this.shrinkWrap = false}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new CommentListState(id, type, shrinkWrap);
  }
}

class CommentListState extends State<CommentList>  {
  final int id;
  final int type;
  final bool shrinkWrap;
  CommentListState(this.id, this.type, this.shrinkWrap,);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int referCount = 0;
  bool isLoadedData = false;

  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildVertical = Dimens.gap_view_normal;
  double paddingChildHorizontal = Dimens.gap_view_normal;
  double portraitSize = Dimens.view_item_icon_height_big;


  List<OscCommentEntity> list;

  RefreshController refreshController;

  @override
  void initState() {
    super.initState();
    refreshController = RefreshController(initialRefresh: true);
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLine();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
        shrinkWrap: shrinkWrap,
      ),
    );
  }

  buildListItem(int index){
    OscCommentEntity item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        print("---ontap");
      },
      child: Container(
        padding: EdgeInsets.only(left: paddingParentHorizontal, right: paddingParentHorizontal, top: paddingParentHorizontal, bottom: paddingParentHorizontal),
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildPortrait(item.author.portrait),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: Dimens.gap_view_normal),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    buildUser(item),
                    CommentReferWidget(refers: item.refer,),
                    buildContentText(item.content),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildUser(OscCommentEntity item){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        buildText(item.author.name, Colors.black, Dimens.font_sp14),
        SmallWidgets.buildLine(color: Colors.transparent, height: Dimens.gap_divider_height_small),
        buildText(item.pubDate, Colors.black54, Dimens.font_sp10),
        SmallWidgets.buildLineBigger(color: Colors.transparent),
      ],
    );
  }

  buildPortrait(String imageUrl){
    return Container(
      width: portraitSize,
      height: portraitSize,
      child: ClipOval(
        child: ImageLoader(url: imageUrl),
      ),
    );
  }

  buildContentText(String text){
    return Padding(
      padding: EdgeInsets.only(top: paddingChildVertical, right: paddingChildVertical),
      child: buildText(StringUtil.clearHtmlContent(text), Colors.black87, Dimens.font_sp14),
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  Future<Null> refresh() async{
    pageToken = null;
    list?.clear();
    return await loadMore();
  }


  Future<Null> loadMore() async{
    isLoadedData = true;
    await httpRepository.getCommentList(id: id, type: type, pageToken: pageToken).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscCommentEntity> result = resp.result;
        if(result != null){
          List<OscCommentEntity> tempList = result.items;
          if(pageToken == null){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          size = list?.length??0;
          pageToken = result.nextPageToken;

          if(result.requestCount > result.responseCount){
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        } else {
          refreshController.loadNoData();
        }
      }
    });
    setState(() {
      refreshController.refreshCompleted();
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
